<script setup lang="ts">
// 搜索表单绑定对象
import {nextTick, onMounted, reactive, ref, Ref} from "vue";
import useDialog from "@/hooks/useDialog.ts";
import SysDialog from "@/components/dialog/SysDialog.vue";
import SelectChecked from "@/components/selectChecked/SelectedChecked.vue";
import {ElMessage, FormInstance} from "element-plus";
import {getSelectApi} from "@/api/role/index.ts";
import {addApi, getListApi, getUserRoleApi, editApi, deleteApi, resetPasswordApi} from "@/api/user/index.ts";
import {getTreeListApi,} from '@/api/dept/index.ts'
import {User, UserListParam} from "@/api/user/type.ts";
// 弹框属性
const {dialog, onShow, onClose, onConfirm} = useDialog()
import useInstance from "@/hooks/useInstance.ts";
import TreeSelect from "@/components/TreeSelect/index.vue";
// 获取全局 global
const {global} = useInstance()


// ----------------------- 树形数据处理 -----------------------
// 上级分类选择器的数据
const parentOptions = ref<any[]>([])

/**
 * 获取部门数据，用于选择人员属于部门
 * 用于新增/编辑表单中的选
 */
const getDeptSelect= async () => {
  try {
    const res = await getTreeListApi()
    if (res?.data) {
      parentOptions.value = res.data
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  }
}


// ----------------------- 左侧筛选树形数据处理 -----------------------
// 定义树节点类型
interface TreeNode {
  id: string
  name: string
  parentId: string
  children: TreeNode[]
}

// 左侧筛选树形数据
const treeData = ref<TreeNode[]>([])

// 当前选中的分类ID，用于树形筛选
const currentId = ref<number>()

/**
 * 获取左侧筛选树形数据
 */
const getTreeData = async () => {
  try {
    const res = await getTreeListApi()
    if (res?.data) {
      treeData.value = res.data
    }
  } catch (error) {
    console.error('获取树形数据失败:', error)
    ElMessage.error('获取部门数据失败')
  }
}

/**
 * 树节点点击事件处理
 */
const handleTreeNodeClick = async (data: any) => {
  // 处理虚拟顶级节点点击
  if (data.id === '-1') {
    currentId.value = undefined
    searchParam.deptId = undefined
  } else {
    currentId.value = data.id
    searchParam.deptId = currentId.value as number
  }

  // 重置分页和搜索条件
  searchParam.page = 1
  searchParam.limit = 10
  await getList()
}
// --------------------------------------------------

// 总条数
const total: Ref<number> = ref(0)

// 搜索表单
const searchParam = reactive(<UserListParam>{
  mobile: '',
  name: '',
  deptId:undefined,
  page: 1,
  limit: 10,
})
// 角色下拉组件Ref
const selectRef = ref()
// 表单ref属性
const addRef = ref<FormInstance>()



// 新增表单绑定对象
const addModel = reactive(<User>{
  id: undefined,
  username: undefined,
  password: undefined,
  mobile: undefined,
  email: undefined,
  gender: 1,
  name: undefined,
  roleId: undefined,
  deptId:undefined,
  maxProject:undefined
})

// 表单校验规则
const rules = reactive({
  username: [
    {required: true, message: '请输入登录账户', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '请输入登录密码', trigger: 'blur'},
  ],
  mobile: [
    {required: true, message: '请输入电话', trigger: 'blur'},
  ],
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
  ],
  gender: [
    {required: true, message: '请选择性别', trigger: 'blur'},
  ],
  name: [
    {required: true, message: '请输入姓名', trigger: 'blur'},
  ],
  roleId: [
    {required: true, message: '请选择角色', trigger: 'blur'},
  ],
  deptId: [
    {required: true, message: '请选择所属部门', trigger: 'blur'},
  ],
})

// 表格高度
const tableHeight = ref()
// 表格数据
const tableData = ref([])

// 新增按钮
const addBtn = () => {
  dialog.title = '新增用户'
  dialog.height = 300
  dialog.width = 750
  // 显示弹框
  onShow()
  // 清理表单
  addRef.value?.resetFields()
  // 清空下拉数据
  getSelect();
  bindValue.value = []
  nextTick(() => {
    selectRef.value?.clear()
  })
  // 清空值
  Object.assign(addModel, {
    id: null,
    username: '',
    password: '',
    mobile: '',
    email: '',
    gender: '1',
    name: '',
  })
}

// 下拉数据
let options = ref([])

// 搜索按钮
const searchBtn = () => {
  getList()
}

// 重置按钮
const resetBtn = () => {
  searchParam.mobile = ''
  searchParam.name = ''
  searchParam.page = 1
  getList()
}

//角色勾选的值
const selected = (value: Array<string | number>) => {
  console.log(value)
  addModel.roleId = value.join(',')
  console.log(addModel.roleId)
}

// 表单提交
const commit = () => {
  addRef.value?.validate(async (valid) => {
    if (valid) {
      console.log('通过')
      try {
        // 提交请求
        if (!addModel.id) {
          const result = await addApi(addModel);
          ElMessage.success('新增用户成功')
        } else {
          const result = await editApi(addModel);
          ElMessage.success('修改用户成功')
        }
        // 刷新列表
        getList()
        // 关闭弹框
        onClose()
      } catch (error) {
      }
    }
  })
}
// 获取角色下拉数据
const getSelect = async () => {
  try {
    const res = await getSelectApi()
    options.value = res.data
  } catch (error) {
    console.log('error', error)
  }
}

// 用户拥有的角色Id
const bindValue = ref([])

// 根据用户id查询用户角色
const getUserRoleList = async (userId: number) => {
  try {
    const result = await getUserRoleApi(userId);
    bindValue.value = result.data
    addModel.roleId = result.data.join(',')
  } catch (error) {
    console.log('error' + error)
  }
}

//列表查询
const getList = async () => {
  try {
    let res = await getListApi(searchParam)
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
  }
}

// 编辑按钮
const editBtn = async (row: User) => {
  console.log(row)
  // 显示弹框
  dialog.title = '编辑用户'
  dialog.height = 300
  dialog.width = 750
  // 显示弹框
  onShow()
  // 清理表单
  addRef.value?.resetFields()
  // 获取下拉数据
  await getSelect()
  // 获取用户拥有的角色
  await getUserRoleList(row.id as number)
  // 回显数据
  Object.assign(addModel, row)
}
// 删除按钮
const deleteBtn = async (userId: number) => {
  const confirm = await global.$myConfirm('此操作将永久删除该用户，是否继续?');
  if (confirm) {
    try {
      const result = await deleteApi(userId)
      ElMessage.success('删除成功')
      // 刷新列表
      getList()
    } catch (error) {
    }
  }
}

// 重置密码
const resetPasswordBtn = async (userId:number)=>{
  const confirm = await global.$myConfirm('确定重置密码吗？重置后密码为【666666】?');
  if (confirm) {
    try {
      const result = await resetPasswordApi(userId)
      ElMessage.success('重置成功')
    } catch (error) {

    }
  }
}


onMounted(() => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 250
  })
  getTreeData()
  getList()
  getDeptSelect()
})
</script>

<template>
  <el-main>
    <el-row :gutter="20">
      <!-- 左侧树形菜单 -->
      <el-col :span="4">
        <TreeSelect :data="treeData"
                    :props="{
              children: 'children',
              label: 'name'
            }"
                    placeholder="请输入部门名称"
                    @node-click="handleTreeNodeClick" />
      </el-col>

      <!-- 右侧内容区 -->
      <el-col :span="20">

        <!--搜索栏-->
        <el-form :model="searchParam" ref="form" :inline="true">
          <el-form-item label="姓名">
            <el-input placeholder="请输入姓名" v-model="searchParam.name"></el-input>
          </el-form-item>

          <el-form-item label="电话">
            <el-input placeholder="请输入电话" v-model="searchParam.mobile"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button icon="Search" @click="searchBtn">搜索</el-button>
            <el-button icon="Close" type="danger" plain @click="resetBtn">重置</el-button>
            <el-button icon="Plus" type="primary" @click="addBtn" v-permission="['sys:user:add']">新增</el-button>
          </el-form-item>
        </el-form>

        <!--表格数据-->
        <el-table :height="tableHeight" :data="tableData" border>
          <el-table-column type="index" label="序号" width="70"/>
          <el-table-column prop="name" label="姓名" />
          <el-table-column prop="username" label="账户" />
          <el-table-column prop="deptName" label="部门">
            <template #default="scope">
              <el-tag type="primary">{{scope.row.deptName}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="gender" label="性别">
            <template #default="scope">
              <el-tag v-if="scope.row.gender == 0" type="primary" effect="dark">女</el-tag>
              <el-tag v-else type="danger" effect="dark">男</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="电话" />
          <el-table-column prop="email" label="邮箱"  width="180"/>
          <el-table-column label="操作" width="250" align="center">
            <template #default="scope">
              <el-button icon="edit" link  size="small" type="primary" @click.prevent="editBtn(scope.row)" v-permission="['sys:user:update']">编辑</el-button>
              <el-button icon="setting" link  size="small" type="warning" @click.prevent="resetPasswordBtn(scope.row.id)" v-permission="['sys:user:restPassword']">重置密码</el-button>
              <el-button icon="delete" link  size="small" type="danger" @click.prevent="deleteBtn(scope.row.id)" v-permission="['sys:user:delete']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--分页器-->
        <div class="pagination">
          <el-pagination
              v-model:current-page="searchParam.page"
              v-model:page-size="searchParam.limit"
              :page-sizes="[10, 15, 20, 30]"
              :background="true"
              layout='prev, pager, next, jumper,->,sizes,total'
              :total="total"
              @size-change="getList"
              @current-change="getList"
          />
        </div>
      </el-col>
    </el-row>




    <!--新增、编辑-->
    <SysDialog
        :title="dialog.title"
        :width="dialog.width"
        :height="dialog.height"
        :visible="dialog.visible"
        @on-close="onClose"
        @on-confirm="commit">
      <template v-slot:content>
        <el-form :model="addModel" ref="addRef" :rules="rules" label-width="85px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名:" prop="name">
                <el-input v-model="addModel.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别:" prop="gender">
                <el-radio-group v-model="addModel.gender">
                  <el-radio value="1" label="男"></el-radio>
                  <el-radio value="0" label="女"></el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="电话:" prop="mobile">
                <el-input v-model="addModel.mobile"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱:" prop="email">
                <el-input v-model="addModel.email"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="角色:" prop="roleId">
                <SelectChecked ref='selectRef' :bindValue="bindValue" :options="options" style="width: 280px"
                               @selected="selected"></SelectChecked>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门:" prop="deptId">
                <el-tree-select v-model="addModel.deptId"
                                :data="parentOptions"
                                :render-after-expand="false"
                                placeholder="请选择所属部门"
                                show-checkbox
                                check-strictly
                                clearable
                                class="flex-1" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="!addModel.id">
            <el-col :span="12">
              <el-form-item label="账户:" prop="username">
                <el-input v-model="addModel.username"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码:" prop="password">
                <el-input v-model="addModel.password"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="!addModel.id">
            <el-col :span="12">
              <el-form-item label="最大项目数:" prop="maxProject">
                <el-input v-model="addModel.maxProject"></el-input>
              </el-form-item>
            </el-col>
     
          </el-row>
        </el-form>
      </template>
    </SysDialog>

  </el-main>
</template>

<style scoped>
.pagination {
  margin-top: 20px;
}
</style>
